package com.educhains.web.ctrl.backend;

import com.alibaba.fastjson.JSONObject;
import com.educhains.module.community.service.CommunityService;
import com.educhains.module.community.vo.Community;
import com.educhains.web.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Controller
public class CummunityMaintain {

    private static final String  TYPE_PATH = "/WEB-INF/jsp/backend/maintain/panelList/communityList.jsp";
    private static final String  TYPE = "community";

    @Autowired
    private CommunityService communityService;


    @RequestMapping(value = "/maintain/communityManage")
    public String communityManage(HttpServletRequest request) {

        List<Community> communityList = communityService.selectCommunityList();


        request.setAttribute("type", TYPE);
        request.setAttribute("typePath", TYPE_PATH);
        request.setAttribute("communityList", communityList);

        return "backend/maintain/operationPanel";

    }

    @ResponseBody
    @RequestMapping(value = "/maintain/communityModify")
    public String communityModify(HttpServletRequest request) {

        String name = request.getParameter("name_content");
        String announcement = request.getParameter("announcement_content");

        communityService.updateAnnounceByName(name, announcement);

        return returnBody(true, "modify successfully");
    }

    private static String returnBody(boolean success, String msg) {
        JSONObject json = new JSONObject();
        if (success) {
            json.put("success", true);
            json.put("msg", msg);
        } else {
            json.put("success", false);
            json.put("msg", msg);
        }
        //return json.toJSONString();
        return JsonUtils.toJSONString(json);
    }
}
